package com.kingmed.kmss.framework.cpwx.service.impl;

import com.google.gson.JsonObject;
import com.kingmed.kmss.framework.cpwx.config.WxCpConfiguration;
import com.kingmed.kmss.framework.cpwx.service.KmWxCpOAuth2Service;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.util.json.GsonHelper;
import me.chanjar.weixin.common.util.json.GsonParser;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpOauth2UserInfo;
import org.apache.http.util.Asserts;
import org.springframework.stereotype.Service;

/**
 * @author liangzhi
 * @date 2024/1/25
 */
@Service
public class KmWxCpOAuth2ServiceImpl implements KmWxCpOAuth2Service {


    public WxCpOauth2UserInfo getUserInfo(Integer agentId, String code) throws WxErrorException {
        WxCpService cpService = WxCpConfiguration.getCpService(agentId);
        Asserts.notNull(cpService, "应用配置异常");
        String responseText = cpService.get(String.format(cpService.getWxCpConfigStorage().getApiUrl("/cgi-bin/auth/getuserinfo?code=%s"), code), (String) null);
        JsonObject jo = GsonParser.parse(responseText);
        return WxCpOauth2UserInfo.builder()
                .userId(GsonHelper.getString(jo, "userid"))
                .openId(GsonHelper.getString(jo, "openid"))
                .userTicket(GsonHelper.getString(jo, "user_ticket"))
                .externalUserId(GsonHelper.getString(jo, "external_userid"))
                .build();
    }

}
